package com.guigu.qingcheng.servicegoods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.qingcheng.pojo.goods.TbSku;
import com.guigu.qingcheng.pojo.order.TbOrderItem;
import com.guigu.qingcheng.servicegoods.mapper.TbSkuMapper;
import com.guigu.qingcheng.servicegoods.service.TbSkuService;
import com.guigu.qingcheng.servicegoods.service.TbSpuService;
import com.guigu.qingcheng.utils.CacheKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbSkuServiceImpl extends ServiceImpl<TbSkuMapper, TbSku> implements TbSkuService {

    @Autowired
    private TbSkuService tbSkuService;

    @Autowired
    private TbSpuService spuService;

    @Autowired
    private RedisTemplate redisTemplate;

    //根据条件查询封装查询对象
    public QueryWrapper<TbSku> queryWrapper(Map<String, Object> searchMap){
        QueryWrapper<TbSku> wapper = new QueryWrapper<TbSku>();
        if(searchMap != null){
            if(searchMap.get("id") != null && !"".equals(searchMap.get("id")))
                wapper.eq("id", searchMap.get("id"));
            if(searchMap.get("name") != null && !"".equals(searchMap.get("name")))
                wapper.like("name", searchMap.get("name"));

            if(searchMap.get("price") != null && !"".equals(searchMap.get("price")))
                wapper.eq("price", searchMap.get("price"));
            if(searchMap.get("num") != null && !"".equals(searchMap.get("num")))
                wapper.eq("num", searchMap.get("num"));

            if(searchMap.get("weight") != null && !"".equals(searchMap.get("weight")))
                wapper.eq("weight", searchMap.get("weight"));
            if(searchMap.get("spuId") != null && !"".equals(searchMap.get("spuId")))
                wapper.eq("spu_id", searchMap.get("spuId"));

            if(searchMap.get("updateTime") != null && !"".equals(searchMap.get("updateTime")))
                wapper.like("update_time", searchMap.get("updateTime"));
            if(searchMap.get("createTime") != null && !"".equals(searchMap.get("createTime")))
                wapper.like("create_time", searchMap.get("createTime"));

            if(searchMap.get("categoryId") != null && !"".equals(searchMap.get("categoryId")))
                wapper.eq("category_id", searchMap.get("categoryId"));
            if(searchMap.get("categoryName") != null && !"".equals(searchMap.get("categoryName")))
                wapper.like("category_name", searchMap.get("categoryName"));

            if(searchMap.get("brandName") != null && !"".equals(searchMap.get("brandName")))
                wapper.like("brand_name", searchMap.get("brandName"));
            if(searchMap.get("spec") != null && !"".equals(searchMap.get("spec")))
                wapper.like("spec", searchMap.get("spec"));

            if(searchMap.get("saleNum") != null && !"".equals(searchMap.get("saleNum")))
                wapper.eq("sale_num", searchMap.get("saleNum"));
            if(searchMap.get("commentNum") != null && !"".equals(searchMap.get("commentNum")))
                wapper.eq("comment_num", searchMap.get("commentNum"));

            if(searchMap.get("status") != null && !"".equals(searchMap.get("status")))
                wapper.eq("status", searchMap.get("status"));
        }
        return wapper;
    }

    @Override
    public Page<TbSku> findPage(Map<String, Object> searchMap, int page, int size) {
        Page<TbSku> pageTbSku = new Page<TbSku>(page, size);
        QueryWrapper<TbSku> query = queryWrapper(searchMap);
        query.eq("status",1);
        IPage<TbSku> list = this.tbSkuService.page(pageTbSku, query);
        return pageTbSku;
    }

    @Override
    public List<TbSku> findList(Map<String, Object> searchMap) {
        QueryWrapper<TbSku> wrapper = queryWrapper(searchMap);
        List<TbSku> list = this.tbSkuService.list(wrapper);
        return list;
    }

    @Override
    public void saveAllPriceToRedis() {
        //检查缓存是否存在价格数据
        if(!redisTemplate.hasKey(CacheKey.SKU_PRICE.toString())){
            System.out.println("加载全部价格");
            List<TbSku> skuList = tbSkuService.list(null);
            for(TbSku sku:skuList){
                if("1".equals(sku.getStatus())){
                    redisTemplate.boundHashOps(CacheKey.SKU_PRICE.toString()).put(sku.getId(),sku.getPrice());
                }
            }
        }else{
            System.out.println("已存在价格数据，没有全部加载");
        }

    }

    @Override
    public Integer findPrice(String id) {
        //从缓存中查询
        System.out.println("从缓存中查询价格");
        return (Integer)redisTemplate.boundHashOps(CacheKey.SKU_PRICE.toString()).get(id);
    }

    @Override
    public void savePriceToRedisById(String id, Integer price) {
        redisTemplate.boundHashOps(CacheKey.SKU_PRICE).put(id,price);
    }

    @Override
    public void deletePriceFromRedis(String id) {
        redisTemplate.boundHashOps(CacheKey.SKU_PRICE).delete(id);
    }

    @Override
    @Transactional
    public boolean deductionStock(List<TbOrderItem> oderItemList) {
        //检查是否可以扣减库存
        boolean flag = true;
        for (TbOrderItem orderItem: oderItemList) {
            TbSku sku = baseMapper.selectById(orderItem.getSkuId());
            if (sku == null) {
                flag = false;
                break;
            }
            if (!"1".equals(sku.getStatus())) {
                flag = false;
                break;
            }
            if (sku.getNum().intValue()<orderItem.getNum().intValue()){
                flag = false;
                break;
            }
        }
        //执行扣减
        if (flag) {
            for (TbOrderItem orderItem:oderItemList) {
                //扣减库存
                baseMapper.deductionStock(orderItem.getSkuId(),orderItem.getNum());
                //增加销量
                baseMapper.addSaleNum(orderItem.getSkuId(),orderItem.getNum());
            }
        }
        return flag;
    }

    /*@Override
    public Boolean ljdelete(String id) {
        //根据id查找对象
        TbSku sku= this.tbSkuService.getById(id);
        //根据sku的spuId找到对应的spu的数据
        TbSpu spu = this.spuService.getById(sku.getSpuId());
        //将状态变成3
        sku.setStatus("3");
        //将删除状态变成1
        spu.setIsDelete("1");
        boolean flag = tbSkuService.updateById(sku);
        boolean b = spuService.updateById(spu);
        if (flag && b){
            return true;
        }
        return false;
    }*/

}
